import { SysDictDataEntity } from './../../entity/sys-dict-data.entity';
import { CreateDictDataDto, CreateDictDto } from './dto/createDict.dto';
import { SysDictEntity } from './../../entity/sys-dict.entity';
import { MenuService } from './menu.service';
import { SysRoleEntity } from './../../entity/sys-role.entity';
import { AuthService } from './../auth/auth.service';
import { CommonRepService } from './../../common/services/commonRep.service';
import { Injectable, forwardRef, Inject, BadRequestException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { PaginationQueryDto } from 'src/common/dto/paginationQuery.dto';

@Injectable()
export class DictService extends CommonRepService<SysDictEntity, CreateDictDto>{

    constructor(
        @InjectRepository(SysDictEntity) private readonly sysDictServ: Repository<SysDictEntity>,
        @InjectRepository(SysDictDataEntity) private readonly sysDicDatatServ: Repository<SysDictDataEntity>,
    ) {
        super(sysDictServ);
    }

    async queryDicts(dto: PaginationQueryDto): Promise<any> {
        const dictRes = await this.pagination(dto);
        for (const dict of dictRes.list) {
            dict['items'] = await this.sysDicDatatServ.find({ dictKey: dict.dictKey });
        }
        return dictRes;
    }

    async addDict(dto: CreateDictDto): Promise<any> {
        const one = await this.sysDictServ.findOne({ dictKey: dto.dictKey });
        if (one) {
            throw new BadRequestException(`字典key“${dto.dictKey}” 已存在！`);
        }
        return this.createOne(dto);
    }

    async addDictData(dto: CreateDictDataDto): Promise<any> {
        const one = await this.sysDicDatatServ.findOne({ dictKey: dto.dictKey, dictName: dto.dictName });
        if (one) {
            throw new BadRequestException(`字典key“${dto.dictKey}”下的“${dto.dictName}” 字典项 已存在！`)
        }
        return this.sysDicDatatServ.save(dto);
    }

    async removeDict(id: string): Promise<any> {
        const one = await this.findOneById(id);
        if (one.dictType === '0') {
            throw new BadRequestException('系统字典不允许删除！');
        }
        return this.deleteById(id);
    }

}
